package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
)

//  [eg: 参考文献 https://www.liwenzhou.com/posts/Go/go_redis/]
//  [eg: https://blog.csdn.net/u014527619/article/details/88232178]



func main() {

	node := []string{
		"10.4.176.34:7001",
		"10.4.176.34:7002",
		"10.4.176.34:7003",
		"10.4.176.34:7004",
		"10.4.176.34:7005",
		"10.4.176.34:7006",
	}
	rdb := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs: node,
		ReadOnly: true,
		RouteByLatency: true,
		RouteRandomly: true,
		PoolSize:     1000,
		PoolTimeout:  2 * time.Minute,
		IdleTimeout:  10 * time.Minute,
		ReadTimeout:  2 * time.Minute,
		WriteTimeout: 1 * time.Minute,
	})
	_, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		panic(err)
	}
	s,err:=rdb.Set(context.Background(),"222","111",0).Result()
	if err!=nil{
		panic(err)
	}
	fmt.Println(s)
	if err :=rdb.Do(context.Background(),"SELECT",1).Err();err!=nil{

	}
	mh :=rdb.Get(context.Background(),"222").Val()
	fmt.Println(mh)
}

// 单节点模式
func SingleClient() (err error) {
	rdb := redis.NewClient(&redis.Options{
		Addr:     "10.4.176.187:7001",
		Password: "",
		DB:       0,
		PoolSize: 100,
	})
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_, err = rdb.Ping(ctx).Result()
	return err
}


// 哨兵模式
func SentinelClient() (err error) {
	rdb := redis.NewFailoverClient(&redis.FailoverOptions{
		MasterName:    "master",
		SentinelAddrs: []string{"x.x.x.x:26379", "xx.xx.xx.xx:26379", "xxx.xxx.xxx.xxx:26379"},
	})
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_, err = rdb.Ping(ctx).Result()
	if err != nil {
		return err
	}
	return nil
}

// 集群模式
func ClusterClient()(err error){
	rdb := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs: []string{":7001", ":7002", ":7003"},
	})
	_, err = rdb.Ping(context.Background()).Result()
	if err != nil {
		return err
	}
	return nil
}